'''
@author: nick mueller
'''

import threading
import exchange_pb2
import time
import util
import RPi.GPIO as GPIO


class ButtonController(threading.Thread):
    '''
    The ButtonController is listening for input events on the GPIO-Ports.
    This controller is running on a new thread.    
    '''
    
    def __init__(self, callback):
        '''
        sets GPIO Port 17 and 27 for inputs.
        Do not forget to start the listening process: startButtonListener() 
        
        @param param: callback 
            is a function pointer and will call on an input event.
            the callback function have to ONE parameter. It will be a 
            Request-Object as a String
        '''
        
        threading.Thread.__init__(self)
        self.callback = callback
        self.__press1 = False
        self.__press2 = False

        self.recordTL = exchange_pb2.Request()
        self.recordTL.type = exchange_pb2.Request.START_CAPTURE

        self.recordMovie = exchange_pb2.Request()
        self.recordMovie.type = exchange_pb2.Request.START_MOVIE_CPT

        # set up GIO Pins
        GPIO.setmode(GPIO.BCM) 
        GPIO.setup(17, GPIO.IN)
        GPIO.setup(27, GPIO.IN)

    def startButtonListener(self):
        '''
        starts the listening process/thread
        '''
        self.start()

    def run(self):
        while True:
            if(GPIO.input(17) == True and self.__press1 == False):
                self.__press1 = True
                util.getLogger().info("Start Timelapse by button")
                self.recordTL.timestamp = str(int(time.mktime(time.gmtime())))
                self.callback(self.recordTL.SerializeToString())
            elif(GPIO.input(17) == False):
                self.__press1 = False
                
            if(GPIO.input(27) == True and self.__press2 == False):
                self.__press2 = True
                util.getLogger().info("Start Movie by button")
                self.recordMovie.timestamp = str(int(time.mktime(time.gmtime())))
                self.callback(self.recordMovie.SerializeToString())
            elif(GPIO.input(27) == False):
                self.__press2 = False
                
